import logging
import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from docx import Document
from docx.shared import Inches
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

tem_path = "temp_static"
tem_url = "zl.sunne.xyz"
# --- 您需要配置的部分 ---
# 1. 将您想要截图的URL列表放在这里
# URLS_TO_CAPTURE = [
#     "https://www.google.com/",
#     "https://www.wikipedia.org/",
#     "https://github.com/"
# ]

# 2. 定义输出的Word文档名称
# OUTPUT_DOCX_FILE = f"web_screenshots.docx"

# 3. 定义一个临时文件夹来存放截图
# IMAGE_FOLDER = "temp_screenshots"


# --- 配置结束 ---


def capture_full_page_screenshot(driver, url, image_path):
    """
    访问URL并截取整个网页的完整长图。
    """
    print(f"正在访问: {url}")
    driver.get(url)

    # 等待页面加载，特别是对于有动态加载内容的页面，这个时间可能需要调整
    # 对于简单的静态页面，2-3秒足够；复杂页面可能需要更长时间
    time.sleep(3)

    print("开始截取完整网页...")
    try:
        # 获取<body>元素的大小，以此来截取整个页面
        # 这种方法比简单的截图命令更能保证截取到整个可滚动区域
        body_element = driver.find_element(By.TAG_NAME, 'body')
        body_element.screenshot(image_path)
        print(f"截图成功，已保存至: {image_path}")
        return True
    except Exception as e:
        print(f"截图失败: {e}")
        return False


def url_img_docx(sc_id:str,task_doc_info:list,title:str,out_put_path:str):
    """
    根据功能列表，标题，生成操作手册
    :param out_put_path:
    :param title:
    :param sc_id:
    :param task_doc_info: 功能简介列表

    :return:
    """
    logging.info(f"[{sc_id}] - 成功进入 url_img_docx 函数。")
    # 1. 准备工作：创建临时图片文件夹
    image_folder = f"{tem_path}/{sc_id}/temp_img"
    if not os.path.exists(image_folder):
        os.makedirs(image_folder)
        print(f"创建临时文件夹: {image_folder}")

    # 2. 初始化Word文档
    doc = Document()
    doc.add_heading(title, 0)
    print("正在添加目录占位符...")
    paragraph = doc.add_paragraph()
    run = paragraph.add_run()
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    instrText = OxmlElement('w:instrText')
    instrText.set(qn('xml:space'), 'preserve')
    instrText.text = 'TOC \\o "1-3" \\h \\z \\u'  # 定义目录包含1-3级标题
    fldChar2 = OxmlElement('w:fldChar')
    fldChar2.set(qn('w:fldCharType'), 'separate')
    fldChar3 = OxmlElement('w:t')
    fldChar3.text = "右键点击更新目录."  # 打开文档后的提示
    fldChar2.append(fldChar3)
    fldChar4 = OxmlElement('w:fldChar')
    fldChar4.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)
    run._r.append(instrText)
    run._r.append(fldChar2)
    run._r.append(fldChar4)

    # 3. 初始化Selenium WebDriver
    # 使用webdriver-manager自动管理ChromeDriver
    print("正在启动浏览器...")
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')  # 无头模式，不在屏幕上显示浏览器窗口
    options.add_argument('--start-maximized')  # 确保窗口足够大以渲染所有元素
    options.add_argument('--disable-gpu')
    options.add_argument('--no-sandbox')

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    driver.set_window_size(1920, 1080)
    #用户跟踪上一个功能模块，用于生成目录
    last_feature_name = None
    # 4. 循环处理每个URL
    for i, task in enumerate(task_doc_info):
        url_path = task['url_path']
        feature_name = task['feature_name']
        feature_description = task['feature_description']
        action_description = task['action_description']
        # 定义每个截图的文件名
        image_name = f"{i}_{feature_name}.png"
        image_path = os.path.join(image_folder, image_name)

        if feature_name != last_feature_name:
            logging.info(f"\n处理新功能模块: {feature_name}")
            doc.add_heading(feature_name, level=2)
            doc.add_paragraph(feature_description)
            last_feature_name = feature_name  # 更新跟踪变量

        # 执行截图
        if capture_full_page_screenshot(driver, url_path, image_path):
            # 5. 将截图添加到Word文档中
            p = doc.add_paragraph()
            p.add_run(action_description).bold = True
            # 添加图片
            doc.add_picture(image_path, width=Inches(6.0))
        else:
            doc.add_heading(f'页面 {i + 1}: {url_path}', level=2)
            doc.add_paragraph(f"无法截取该页面的截图。")
            doc.add_page_break()
    # 6. 关闭浏览器
    driver.quit()
    print("浏览器已关闭。")

    # 7. 保存Word文档
    doc.save(out_put_path)
    print(f"所有操作完成！Word文档已保存为: {out_put_path}")
